package com.huluobo.a2109monthdemo2.detail

import android.content.Context
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2109monthdemo2.R
import com.huluobo.a2109monthdemo2.base.BaseMVVMActivity
import com.huluobo.a2109monthdemo2.databinding.ActivityDetailBinding
import com.huluobo.a2109monthdemo2.net.Const
import com.huluobo.a2109monthdemo2.utils.ImageUtils
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class DetailActivity : BaseMVVMActivity<ActivityDetailBinding>() {
    private lateinit var viewModel: DetailViewModel
    private var goodsId = 0
    override fun initData() {
        viewModel = ViewModelProvider(this)[DetailViewModel::class.java]
        goodsId = intent.getIntExtra(Const.PARAM_GOODS_ID, 0)

        viewModel.getGoodsDetail(goodsId)

        viewModel.success.observe(this) {
            if (it.code == 200) {
                dataBinding.goods = it.data
                dataBinding.detailBanner.setImages(it.data.bannerList)
                dataBinding.detailBanner.start()
            } else {
                ToastUtils.showLong("详情加载失败:${it.message}")
            }
        }

        viewModel.failed.observe(this) {
            Log.i("TagA", "请求详情失败:$it")
        }

        viewModel.addToCartSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong(it.message)
            } else {
                ToastUtils.showLong("添加购物车失败:${it.message}")
            }
        }

        viewModel.addToCartFailed.observe(this) {
            ToastUtils.showLong("添加购物车失败:$it")
        }
    }

    override fun initView() {
        //初始化banner
        dataBinding.detailBanner.setBannerStyle(BannerConfig.NUM_INDICATOR)
        dataBinding.detailBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    ImageUtils.loadImage(context, path.toString(), imageView)
                }
            }
        })
        dataBinding.detailBanner.setDelayTime(2000)
        dataBinding.detailBanner.setIndicatorGravity(BannerConfig.CENTER)

        dataBinding.detailAddToCart.setOnClickListener {
            viewModel.addToCart(goodsId, 1)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_detail
}